package com.nai365.nart.blockchain.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nai365.nart.blockchain.entity.Account;
import com.nai365.nart.blockchain.mapper.AccountMapper;
import com.nai365.nart.blockchain.service.AccountService;
import com.reddate.wuhanddc.DDCSdkClient;
import com.reddate.wuhanddc.net.DDCWuhan;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.utils.Numeric;

import java.util.UUID;

@Configuration
@AllArgsConstructor
@Component
public class DDCClinet {

	private final AccountMapper accountMapper;

	static {
		DDCWuhan.setGatewayUrl("https://opbningxia.bsngate.com:18602/api/edf44f6dcaef47a38b3743fa3837820c/rpc");
	}

	@Bean
	public DDCSdkClient dDCSdkClient() {
		return new DDCSdkClient().instance((event) -> {
			LambdaQueryWrapper<Account> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.eq(Account::getAddress, event.sender);
			Account account = accountMapper.selectOne(queryWrapper);
			String privateKey = account.getPrivateKey();
			Credentials credentials = Credentials.create(privateKey);
			byte[] signedMessage = TransactionEncoder.signMessage(event.getRawTransaction(), 5555, credentials);
			return Numeric.toHexString(signedMessage);
		});
	}


}
